package cfca.seal.mananger;

import cfca.seal.bean.Seal;
import cfca.seal.common.LRUCache;
import cfca.seal.dao.main.ISealDao;
import cfca.seal.exception.CodeException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SealManager
{
  private static final Logger log = LoggerFactory.getLogger("web_sys");
  static final int cacheSize = 200;
  private static LRUCache<String, Seal> sealMap = new LRUCache(200);
  private static SealManager instance = null;

  @Resource
  ISealDao dao;

  public static SealManager getInstance() { if (instance == null) {
      instance = new SealManager();
    }
    return instance;
  }

  public void init(ServletContext servletContext)
    throws CodeException
  {
    try
    {
      synchronized (this) {
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        this.dao = ((ISealDao)wac.getBean(ISealDao.class));
        List<Seal> list = this.dao.getAll();
        if ((list != null) && (list.size() > 0)) {
          for (Seal seal : list) {
            if (1 == seal.getStatus()) {
              sealMap.put(seal.getCode(), seal);
            }
          }
        }
      }
    }
    catch (Exception e)
    {
      log.error("取得印章信息失败", e);
      throw new CodeException("C0001", e);
    }
  }

  public Seal getSealByCode(String sealCode) throws CodeException {
    try {
      Seal seal = (Seal)sealMap.get(sealCode);
      if (seal != null) {
        if (1 == seal.getStatus()) {
          return seal;
        }
      } else {
        seal = this.dao.getSealByCode(sealCode);
        if ((null != seal) && 
          (1 == seal.getStatus())) {
          sealMap.put(seal.getCode(), seal);
          return seal;
        }
      }

      return null;
    } catch (Exception e) {
      log.error("取得印章信息失败", e);
      throw new CodeException("C0001", e);
    }
  }

  public void addSeal(Seal seal) throws CodeException {
    synchronized (this) {
      sealMap.put(seal.getCode(), seal);
      log.info("印章管理容器增加新的印章:" + seal.getCode());
    }
  }

  public void updateStatus(String id, String status) {
    synchronized (this) {
      for (Seal seal : sealMap.getAll()) {
        if (id.equals(seal.getId())) {
          if (String.valueOf(1).equals(status)) {
            PdfSealManager.getInstance().addPdfSeal(seal); break;
          }
          PdfSealManager.getInstance().removePdfSeal(seal.getCode());

          break;
        }
      }
    }
  }
}